import React from 'react'
import {
    View, StyleSheet, FlatList, Platform, findNodeHandle, UIManager
} from 'react-native'

import CommunityMediaGatherCellView from './CommunityMediaGatherCellView'

const length = Platform.isPad ? 200 : 100
const margin = Platform.isPad ? 10 : 5

export default class CommunityMediaGatherCell extends React.PureComponent {

    render() {
        if (this.props.data.img == null) return null
        var dataList = this.props.data.img
        if (this.props.data.img.length > 3) {
            dataList = this.props.data.img.slice(0, 3)
        }
        // console.log('dataList = ' + dataList)
        let width = dataList.length * (margin + length)
        return (
            <View style={styles.container}>
                <FlatList
                    ref='flatList'
                    style={{ width: width, height: length }}
                    renderItem={this.renderItem}
                    data={dataList}
                    keyExtractor={this.keyExtractor}
                    horizontal={true}
                    alwaysBounceHorizontal={false}
                    showsHorizontalScrollIndicator={false}
                    extraData={this.state}
                />
            </View>
        )
    }

    keyExtractor = (item, index) => '' + index;

    renderItem = ({ item, index }) => {
        return (
            <CommunityMediaGatherCellView data={this.props.data} length={length} margin={margin} item={item} index={index} clickImgAction={this.clickImgAction}/>
        )
    }

    clickImgAction = (data, radius, idx) => {
        const handle = findNodeHandle(this.refs.flatList)
        var imgs = []
        UIManager.measureInWindow(handle, (x, y, width, height) => {
            for (var i = 0; i < data.img.length; i++) {
                let dict = JSON.parse(JSON.stringify(data.img[i]))
                var j
                if (i > 2) {
                    j = 2
                } else {
                    j = i
                }
                let originX = x + j * (length + margin)
                let frame = '{{' + originX + ', ' + y + '}, {' + length + ', ' + length + '}}'
                dict.frame = frame
                dict.idx = i
                imgs.push(dict)
            }
            this.props.clickImgAction(data, imgs, radius, idx)
        })
    }
}

const styles = StyleSheet.create({
    container: {
        marginLeft: 10,
        marginRight: 10,
        marginBottom: 5,
        marginTop:5
    },
})